#include <stdlib.h>
#include <GL/glut.h>
#include "BaseEmitter.hpp"
#include "../ResourceManagers/TextureManager.hpp"
#include "../ResourceManagers/TextureObject.hpp"
#include "../Extensions/ExtensionsLoader.hpp"

using namespace std;

BaseEmitter::BaseEmitter()
{
	m_spawnLimit = DEFAULT_SPAWN_LIMIT;
	m_spawnFreq  = DEFAULT_SPAWN_FREQ;
}

BaseEmitter::BaseEmitter(string fileName, unsigned int limit, int freq)
{
	m_particImage = fileName;
	m_spawnLimit = limit;
	m_spawnFreq  = freq;

	TextureManager::GetInstance()->LoadTexture(fileName, TEXTURE_ALPHA);

	for(int i = 0; i < freq; ++i)
		SpawnParticle();
}

BaseEmitter::~BaseEmitter()
{
	vector<Particle*>::iterator begin = m_particles.begin();
	vector<Particle*>::iterator end   = m_particles.end();

	for(begin; begin != end; ++begin)
	{
		delete *begin;
		*begin = NULL;
	}
}

void BaseEmitter::SetSpawnLimit(unsigned int limit)
{
	m_spawnLimit = limit;
}

void BaseEmitter::SetSpawnFreq(int freq)
{
	m_spawnFreq = freq;
}

void BaseEmitter::SpawnParticle()
{
	Particle* newParticle = new Particle();
	m_particles.push_back(newParticle);
}

void BaseEmitter::Update(clock_t tick)
{
	if(m_particles.size() < m_spawnLimit)
		SpawnParticle();

	vector<Particle*>::iterator currParticle   = m_particles.begin();
	vector<Particle*>::iterator endOfParticles = m_particles.end();

	//for(currParticle; currParticle != endOfParticles; ++currParticle)
	//{
	//	if( (*currParticle)->IsParticleDead() )
	//	{
	//		//delete *currParticle;
	//		//*currParticle = NULL;

	//		m_particles.erase(currParticle);
	//	}
	//}


	currParticle = m_particles.begin();

	for(currParticle; currParticle != endOfParticles; ++currParticle)
	{
		if( !(*currParticle)->IsParticleDead() )
			(*currParticle)->Update(tick);
	}
}

void BaseEmitter::SetParticleImage(string fileName)
{
	m_particImage = fileName;
}

void BaseEmitter::Render()
{
	glPushMatrix();

	glTranslatef(0.0, 50.0 , 0.0);

	TextureObject* texture = (TextureObject*)TextureManager::GetInstance()->GetTexture(m_particImage);

	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture->GetTextureID());
	ExtensionsLoader::glActiveTextureARB(GL_TEXTURE0_ARB);

	vector<Particle*>::iterator currParticle = m_particles.begin();
	vector<Particle*>::iterator endOfParticles = m_particles.end();

	for(currParticle; currParticle != endOfParticles; ++currParticle)
	{
		if( !(*currParticle)->IsParticleDead() )
			(*currParticle)->Render();
	}

	glDisable(GL_TEXTURE_2D);

	glPopMatrix();
}

bool BaseEmitter::isDepleted()
{
	if(m_particles.size() >= m_spawnLimit)
		return true;

	return false;
}

//EOF
